<?php
namespace Controllers\Admin;
use App;
use Config\Base as Config;
use DB\ArticleService;
use DB\FacebookService;
use DB\UserService;

/**
 * @author Evgeny Baranov <evgeny@baranov.eu>
 */
class Article extends Base {

    /**
     * @var \DB\ArticleService
     */
    protected $articleService;

    /**
     * @var \DB\UserService
     */
    protected $userService;

    /**
     * @var FacebookService
     */
    protected $facebookService;

    public function __construct() {
        $this->articleService = new ArticleService();
        $this->userService = new UserService();
        $this->facebookService = new FacebookService();
    }

    public function create(array $param) {
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You have no permission to create article.");
        }
        $this->setView('Article')->setTmpl('edit.phtml');
        $res = array();
        foreach (Config::instance()->lang->list as $l) {
            $res[$l] = new \Models\Article(array(
                'language_code' => $l,
                'annotation' => '',
                'content' => '',
                'author' => $user,
                'author_id' => $user->getId()
            ));
        }

        $back = isset($_GET['back']) ? $_GET['back'] : (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '/');

        return array(
            'list' => $res,
            'back' => $back,
            'albums' => $this->facebookService->getPageAlbums()
        );

    }

    public function edit(array $param) {
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You have no permission to edit article.");
        }
        $id = intval(array_shift($param));
        $data = $this->articleService->getById($id);
        $this->setView('Article')->setTmpl('edit.phtml');

        if (count($data) < 1) {
            throw new \Exception("Article with id {$id} not found.");
        }
        $res = array();
        foreach (Config::instance()->lang->list as $l) {
            foreach ($data as $a) {
                if ($a->getContent()->getLanguageCode() == $l) {
                    $res[$l] = $a;
                    break;
                }
            }
            if (!isset($res[$l])) {
                $a = $data[0]->toArray();
                $a = array_merge($a, array(
                    'article_id' => $a['id'],
                    'language_code' => $l,
                    'path' => '',
                    'title' => '',
                    'content' => '',
                    'created' => '',
                    'updated' => ''
                ));
                $a = new \Models\Article($a);
                $res[$l] = $a;
            }
        }

        $back = isset($_GET['back']) ? $_GET['back'] : (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '/');

        $fb = new FacebookService();
        return array(
            'list' => $res,
            'back' => $back,
            'albums' => $fb->getPageAlbums()
        );
    }

    public function save(array $param) {
        $this->apply(array());
    }

    public function apply(array $param) {
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You have no permission to edit article.");
        }

        $data = $_POST;
        $data['id'] = $data['article_id'];
        if (empty($data['path'])) {
            $data['path'] = $data['title'];
        }
        $data['path'] = mb_strtolower($data['path']);

        $data['path'] = trim(preg_replace('/[\s\.\:\;\?]+/', '_', $data['path']), '_');

        if ($data['id'] == 0) {
            $data['author'] = $user;
            $data['author_id'] = $user->getId();
        }

        if ($data['author_id'] && empty($data['author'])) {
            $data['author'] = $this->userService->getUser($data['author_id']);
        }

        if ($data['album_id'] && empty($data['album'])) {
            $data['album'] = $this->facebookService->getAlbum($data['album_id']);
        }

        $article = new \Models\Article($data);
        $article = $this->articleService->saveArticle($article);

        $this->jsonSuccess($article->toArray());
    }

    public function revert(array $param) {
        $id = $_POST['article_id'];
        try {
            $article = $this->articleService->getById($id, \App::getLang());
        } catch (\Exception $e) {
            $this->jsonError($e->getMessage());
        }
        $article = array_shift($article);

        $this->jsonSuccess($article->toArray());
    }

    public function hide(array $param) {
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You are not authorized.");
        }
        $id = intval(array_shift($param));
        $a = array_shift($this->articleService->getById($id));

        if (!$a->cando($a::OP_WRITE, $user)) {
            \App::error(403, "You have no write permissions for this article.");
        }

        $this->articleService->hideArticle($a);

        $back = isset($_SERVER['HTTP_REFERER']) && ($back = $_SERVER['HTTP_REFERER']) ? $back : '/';
        header('Location: ' . $back);
        exit;
    }

    public function remove_banner(array $param) {
        $id = intval(array_shift($param));
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You are not authorized.");
        }

        $a = array_shift($this->articleService->getById($id));

        if (!$a->cando($a::OP_WRITE, $user)) {
            \App::error(403, "You have no write permissions for this article.");
        }
        $banner = $a->getBanner();
        $this->articleService->removeAttachment($banner);

        $back = isset($_SERVER['HTTP_REFERER']) && ($back = $_SERVER['HTTP_REFERER']) ? $back : '/';
        header('Location: ' . $back);
    }

    public function remove(array $param) {
        $user = \App::getCurrentUser();
        if (!$user) {
            \App::error(403, "You have no permission to delete article.");
        }
        $id = intval(array_shift($param));
        $a = array_shift($this->articleService->getById($id));

        if (!$a->cando($a::OP_WRITE, $user)) {
            \App::error(403, "You have no permission to delete article.");
        }
        $this->articleService->deleteArticle($a);

        $back = isset($_SERVER['HTTP_REFERER']) && ($back = $_SERVER['HTTP_REFERER']) ? $back : '/';
        header('Location: ' . $back);
        exit;
    }

}
